//
//  XGRegisterViewController.m
//  HuanXin
//
//  Created by monkey on 2019/7/8.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <SVProgressHUD/SVProgressHUD.h>
#import <Hyphenate/Hyphenate.h>

#import "XGRegisterViewController.h"

#import "MBProgressHUD+Extension.h"

NSString * const XGRegisterSuccessNotificationName = @"XGRegisterSuccessNotificationName";

@interface XGRegisterViewController ()

/// 用户名
@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
/// 密码
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@end

@implementation XGRegisterViewController

#pragma mark - 控制器生命周期方法

- (void)dealloc
{
    DEBUG_Log_Method;
}

#pragma mark - 事件监听

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

// 注册事件
- (IBAction)registerAction:(UIButton *)button
{
    [self.view endEditing:YES];
    
    if (!_userNameTextField.hasText || !_passwordTextField.hasText) {
        [SVProgressHUD showErrorWithStatus:@"用户名或密码为空"];
        return;
    }
    
    NSString *userName = [_userNameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *password = [_passwordTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [MBProgressHUD showMessage:@"正在注册…" toView:self.view];
    [[EMClient sharedClient] registerWithUsername:userName password:password completion:^(NSString *aUsername, EMError *aError) {
        [MBProgressHUD hideHUD];
        if (aError != nil) {
            DEBUG_Log(@"注册失败%@",aError.errorDescription);
            [SVProgressHUD showErrorWithStatus:@"注册失败"];
            return;
        }
        
        // 发布通知 注册成功
        [[NSNotificationCenter defaultCenter] postNotificationName:XGRegisterSuccessNotificationName object:nil userInfo:@{@"userName": self->_userNameTextField.text,@"password": self->_passwordTextField.text}];
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
}

// 退出事件
- (IBAction)goBackAction:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
